package com.treeliked.service.impl;

import com.treeliked.pojo.FileModel;
import com.treeliked.pojo.Response;
import com.treeliked.service.FolderService;
import com.treeliked.util.FileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件夹操作服务实现
 *
 * @author lqs2
 * @date 2018/11/29, Thu
 */
public class FolderServiceImpl implements FolderService {

    @Override
    public void createFolder(String folderName, Response response) throws Exception {
        File file = new File(folderName);
        response.setCode(Response.RESPONSE_OK);
        if (file.isDirectory()) {
            response.setMessage("文件夹【" + folderName + "】已经存在");
            return;
        }
        boolean success = file.mkdirs();
        if (success) {
            response.setMessage("文件夹【" + folderName + "】创建成功");
        } else {
            response.setMessage("文件夹【" + folderName + "】创建失败");
        }
    }

    @Override
    public void deleteFolder(String folderName, Response response) throws Exception {
        File file = new File(folderName);
        response.setCode(Response.RESPONSE_OK);
        if (!file.exists()) {
            response.setMessage("【" + folderName + "】不存在");
            return;
        }
        if (file.isFile()) {
            response.setMessage("【" + folderName + "】是一个文件");
            return;
        }
        boolean success = FileUtils.deleteFolder(file);
        if (success) {
            response.setMessage("文件夹【" + folderName + "】删除成功");
        } else {
            response.setMessage("文件夹【" + folderName + "】删除失败");
        }
    }

    @Override
    public Map<String, FileModel> displayFolder(String folderName, Response response) throws Exception {
        File file = new File(folderName);
        response.setCode(Response.RESPONSE_OK);
        if (!file.exists()) {
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            response.setMessage("【 " + folderName + "】不存在");
            return null;
        }
        if (file.isFile()) {
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            response.setMessage("【 " + folderName + "】是一个文件");
            return null;
        }
        response.setMessage("列出路径【 " + folderName + "】下的所有内容，【0代表文件，1代表文件夹】");

        Map<String, FileModel> model = new HashMap<>(128);
        FileUtils.displayFolderContent(file, model);
        response.setData(model);
        return model;

    }


}
